import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 所有的任务列表
    list: [],
    // 文本框的内容
    inputValue: '',
    // 下一个 ID
    nextId: 5,
    currentkey: 'All'

  },
  mutations: {
    initList (state, list) {
      state.list = list
    },
    // 当 input 栏数据的双向绑定
    setInputeValue (state, val) {
      state.inputValue = val
    },
    // 添加 项 到列表中
    addItem (state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    // 删除一个指定 ID 的项
    removeItem (state, id) {
      // 傻乎乎的办法
      // const i = state.list.filter((item) => {
      //   return item.id === id
      // })
      // const item = state.list.indexOf(i[0])

      // if (item !== -1) {
      //   state.list.splice(item, 1)
      // }
      const i = state.list.findIndex(x => x.id === id)
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    },
    // 每一项的 done 进行双向绑定
    statusChanged (state, param) {
      const i = state.list.findIndex(x => x.id === param.id)
      if (i !== -1) {
        state.list[i].done = param.done
      }
    },
    // 清除已完成
    cleanDone (state) {
      state.list = state.list.filter(item => item.done === false)
    },
    // 当前选中按钮
    currentButton (state, key) {
      state.currentkey = key
    }
  },
  actions: {
    // 获取列表信息
    getList (context) {
      axios.get('/list.json').then(({ data }) => {
        context.commit('initList', data)
      })
    }
  },
  getters: {
    unDoneLength (state) {
      return state.list.filter(item => item.done === false).length
    },
    infoList (state) {
      if (state.currentkey === 'Undone') {
        return state.list.filter(item => item.done === false)
      } else if (state.currentkey === 'Done') {
        return state.list.filter(item => item.done === true)
      } else {
        return state.list
      }
    }
  }
})
